<template>
	<view class="container">
		<!-- 标签切换 -->
		<view class="tabs">
			<view class="tab-item" 
				  :class="{ active: activeTab === 0 }" 
				  @click="switchTab(0)">
				收到申请
			</view>
			<view class="tab-item" 
				  :class="{ active: activeTab === 1 }" 
				  @click="switchTab(1)">
				我的申请
			</view>
			<!-- 滑动指示器 - 调整位置计算方式 -->
			<view class="tab-line" :style="{ left: tabLinePosition }"></view>
		</view>
		
		<!-- 内容区域 - 使用scroll-view实现下拉刷新 -->
		<scroll-view 
			scroll-y
			class="records-scroll"
			@scrolltoupper="onPullDown"
			refresher-enabled
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
			refresher-background="#f5f5f5"
			>
			
			<!-- 我的兑换列表 -->
			<view v-if="activeTab === 0">
				<view v-if="exchangeList.length === 0 && !loading" class="empty-tip">
					暂无兑换记录
				</view>
                
                <!-- 加载指示器 -->
                <view v-if="loading" class="loading-container">
                    <view class="loading-spinner"></view>
                    <text>加载中...</text>
                </view>
				
				<view v-else class="record-list">
					<view class="record-item" v-for="(item, index) in exchangeList" :key="index">
						<!-- 主信息区 -->
						<view class="item-main">
							<!-- 左侧商品图 -->
							<image class="goods-image" :src="item.goodsImg || '/static/img/default_goods.png'" mode="aspectFill"></image>
							
							<!-- 中间信息区 -->
							<view class="item-info-wrapper">
								<view class="goods-title-line">
									<text class="goods-name">{{item.goodsName}}</text>
									<text class="goods-code">x{{item.quantity}}</text>
								</view>
								<view class="item-info">
									<text class="info-label">兑换用户: </text>
									<text class="info-content">{{item.userName}}({{item.userPhone}})</text>
								</view>
								<view class="item-info">
									<text class="info-label">申请时间: </text>
									<text class="info-content">{{item.createDate}}</text>
								</view>
								<view class="item-info">
									<text class="info-label">获得积分: </text>
									<text class="info-content">{{item.consumptionPoints}}积分</text>
								</view>
							</view>
						</view>
						
						<!-- 积分信息（独立一行，靠右） -->
						<view class="item-points">
							<image class="points-icon" src="/static/img/icon_points.png" mode="aspectFit"></image>
							<text class="points-value">{{item.consumptionPoints}}积分</text>
						</view>
						
						<!-- 操作按钮 -->
						<view class="item-actions">
							<template v-if="item.orderStatus === '2'">
								<view class="action-btn complete-btn">
									<image class="action-icon" src="/static/img/icon_complete.png" mode="aspectFit"></image>
									<text>已完成</text>
								</view>
								<view class="action-btn detail-btn" @click="viewDetail(item)">
									<image class="action-icon" src="/static/img/icon_detail.png" mode="aspectFit"></image>
									<text>兑换详情</text>
								</view>
							</template>
							<template v-if="item.orderStatus === '3'">
								<view class="action-btn complete-btn">
									<image class="action-icon" src="/static/img/icon_complete.png" mode="aspectFit"></image>
									<text>已取消</text>
								</view>
								<view class="action-btn detail-btn" @click="viewDetail(item)">
									<image class="action-icon" src="/static/img/icon_detail.png" mode="aspectFit"></image>
									<text>兑换详情</text>
								</view>
							</template>
							<template v-if="item.orderStatus === '0' || item.orderStatus === '1'">
								<view class="action-btn approve-btn" @click="handleApprove(item)">
									<image class="action-icon" src="/static/img/icon_approve.png" mode="aspectFit"></image>
									<text>待兑换</text>
								</view>
								<view class="action-btn cancel-btn" @click="handleCancel(item)" v-if="item.orderStatus === '0'">
									<image class="action-icon" src="/static/img/icon_cancel.png" mode="aspectFit"></image>
									<text>取消</text>
								</view>
								<view class="action-btn detail-btn" @click="viewDetail(item)">
									<image class="action-icon" src="/static/img/icon_detail.png" mode="aspectFit"></image>
									<text>兑换详情</text>
								</view>
							</template>
						</view>
					</view>
				</view>
				
				<!-- 加载更多/无更多 -->
				<view class="load-more" v-if="exchangeList.length > 0">
					<text v-if="loadingMore">加载中...</text>
					<text v-else>暂无更多</text>
				</view>
			</view>
			
			<!-- 我的申请列表 -->
			<view v-if="activeTab === 1">
				<view v-if="applyList.length === 0 && !loading" class="empty-tip">
					暂无申请记录
				</view>
                
                <!-- 加载指示器 -->
                <view v-if="loading" class="loading-container">
                    <view class="loading-spinner"></view>
                    <text>加载中...</text>
                </view>
				
				<view v-else class="record-list">
					<!-- 申请记录项 -->
					<view class="record-item" v-for="(item, index) in applyList" :key="index">
						<!-- 主信息区 -->
						<view class="item-main">
							<!-- 左侧商品图 -->
							<image class="goods-image" :src="item.goodsImg || '/static/img/default_goods.png'" mode="aspectFill"></image>
							
							<!-- 中间信息区 -->
							<view class="item-info-wrapper">
								<view class="goods-title-line">
									<text class="goods-name">{{item.goodsName}}</text>
									<text class="goods-code">x{{item.quantity}}</text>
								</view>
								<view class="item-info">
									<text class="info-label">提交时间: </text>
									<text class="info-content">{{item.createDate}}</text>
								</view>
								<view class="item-info">
									<text class="info-label">兑换方式: </text>
									<text class="info-content">{{item.methodExchange === '0' ? '当面兑换' : '快递邮寄'}}</text>
								</view>
								<view class="item-info">
									<text class="info-label">使用积分: </text>
									<text class="info-content">{{item.consumptionPoints}}积分</text>
								</view>
							</view>
						</view>
						
						<!-- 积分信息（独立一行，靠右） -->
						<view class="item-points">
							<image class="points-icon" src="/static/img/icon_points.png" mode="aspectFit"></image>
							<text class="points-value">{{item.consumptionPoints}}积分</text>
						</view>
						
						<!-- 操作按钮 -->
						<view class="item-actions">
							<template v-if="item.orderStatus === '2'">
								<view class="action-btn complete-btn">
									<image class="action-icon" src="/static/img/icon_complete.png" mode="aspectFit"></image>
									<text>已完成</text>
								</view>
								<view class="action-btn detail-btn" @click="viewDetail(item)">
									<image class="action-icon" src="/static/img/icon_detail.png" mode="aspectFit"></image>
									<text>兑换详情</text>
								</view>
							</template>
							<template v-if="item.orderStatus === '3'">
								<view class="action-btn complete-btn">
									<image class="action-icon" src="/static/img/icon_complete.png" mode="aspectFit"></image>
									<text>已取消</text>
								</view>
								<view class="action-btn detail-btn" @click="viewDetail(item)">
									<image class="action-icon" src="/static/img/icon_detail.png" mode="aspectFit"></image>
									<text>兑换详情</text>
								</view>
							</template>
							<template v-if="item.orderStatus === '0' || item.orderStatus === '1'">
								<view class="action-btn approve-btn" >
									<image class="action-icon" src="/static/img/icon_approve.png" mode="aspectFit"></image>
									<text>兑换中</text>
								</view>
								<view class="action-btn cancel-btn" @click="handleCancel(item)" v-if="item.orderStatus === '0'">
									<image class="action-icon" src="/static/img/icon_cancel.png" mode="aspectFit"></image>
									<text>取消</text>
								</view>
								<view class="action-btn detail-btn" @click="viewDetail(item)">
									<image class="action-icon" src="/static/img/icon_detail.png" mode="aspectFit"></image>
									<text>兑换详情</text>
								</view>
							</template>
						</view>
					</view>
				</view>
				
				<!-- 加载更多/无更多 -->
				<view class="load-more" v-if="applyList.length > 0">
					<text v-if="loadingMore">加载中...</text>
					<text v-else>暂无更多</text>
				</view>
			</view>
			
		</scroll-view>
		
	</view>
</template>

<script>
	const api = require('../../../config/api');
	const util = require('../../../utils/util');
	
	export default {
		data() {
			return {
				activeTab: 0,  // 0: 我的兑换, 1: 我的申请
				pageNo: 1,     // 当前页码
				pageSize: 10,  // 每页条数，增加为20减少请求次数
				exchangeList: [], // 兑换记录列表
				applyList: [],    // 申请记录列表
				refreshing: false, // 是否正在刷新
				loadingMore: false, // 是否正在加载更多
				loading: true,     // 是否正在加载数据（初始加载）
				hasMore: true,      // 是否有更多数据
				totalPages: 1,      // 总页数
				loadingAllData: false // 是否正在加载所有数据
			}
		},
        computed: {
            // 标签指示器位置计算
            tabLinePosition() {
                // 更精确地计算指示器位置，确保在文字中间
                return this.activeTab === 0 ? '25%' : '75%';
            }
        },
		onShow() {
			// 当系统下拉刷新被触发
			this.onRefresh();
		},
		onLoad() {
			// 确保页面加载时自动获取数据
			this.loading = true;
			this.loadAllExchangeData();
		},
		// 页面下拉刷新
		onPullDownRefresh() {
			// 当系统下拉刷新被触发
			this.onRefresh();
		},
		// 页面上拉触底
		onReachBottom() {
			// 加载更多数据
			this.loadMore();
		},
		methods: {
			// 切换标签
			switchTab(index) {
				if (this.activeTab === index) return;
				this.activeTab = index;
				this.pageNo = 1;
				this.loading = true;
				this.loadingAllData = false;
				this.totalPages = 1;
				
				// 根据当前标签加载对应数据
				if (index === 0) {
					this.loadAllExchangeData();
				} else {
					this.loadAllApplyData();
				}
			},
			
			// 下拉刷新触发
			onPullDown() {
				if (this.refreshing) return;
				this.onRefresh();
			},
			
			// 刷新数据
			onRefresh() {
				this.refreshing = true;
				this.pageNo = 1;
				this.loadingAllData = false;
				this.totalPages = 1;
				
				// 根据当前标签刷新对应数据
				if (this.activeTab === 0) {
					this.loadAllExchangeData();
				} else {
					this.loadAllApplyData();
				}
			},
			
			// 加载更多
			loadMore() {
				if (this.loadingMore || !this.hasMore) return;
				
				this.loadingMore = true;
				this.pageNo++;
				
				// 根据当前标签加载更多对应数据
				if (this.activeTab === 0) {
					this.loadExchangeData(false);
				} else {
					this.loadApplyData(false);
				}
			},
			
			// 加载所有兑换记录
			async loadAllExchangeData() {
				try {
					this.loadingAllData = true;
					// 重置列表
					this.exchangeList = [];
					this.pageNo = 1;
					
					// 首次加载
					await this.loadExchangeData(true);
					
					// 继续加载剩余页
					while (this.pageNo < this.totalPages) {
						this.pageNo++;
						await this.loadExchangeData(false);
					}
				} catch (error) {
					console.error('加载所有兑换记录失败:', error);
				} finally {
					this.loadingAllData = false;
					this.refreshing = false;
					this.loadingMore = false;
					this.loading = false;
					uni.stopPullDownRefresh();
				}
			},
			
			// 加载所有申请记录
			async loadAllApplyData() {
				try {
					this.loadingAllData = true;
					// 重置列表
					this.applyList = [];
					this.pageNo = 1;
					
					// 首次加载
					await this.loadApplyData(true);
					
					// 继续加载剩余页
					while (this.pageNo < this.totalPages) {
						this.pageNo++;
						await this.loadApplyData(false);
					}
				} catch (error) {
					console.error('加载所有申请记录失败:', error);
				} finally {
					this.loadingAllData = false;
					this.refreshing = false;
					this.loadingMore = false;
					this.loading = false;
					uni.stopPullDownRefresh();
				}
			},
			
			// 加载兑换记录数据
			async loadExchangeData(reset = false) {
				try {
					// 如果已经在加载所有数据，则不重置页码和刷新状态
					if (reset && !this.loadingAllData) {
						this.pageNo = 1;
					}
					
					const token = uni.getStorageSync('token');
					if (!token) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						return;
					}
					
					const requestData = {
						page: this.pageNo,
						limit: this.pageSize,
						type: "0" // 0 表示我的兑换
					};
					
					// 调用接口，保持与GoodsDetails一致的请求风格
					const res = await util.request(
						api.integralExchangeRecordUrl,
						requestData,
						'POST'
					);
					
					console.log('兑换记录数据:', res);
					
					if (res.code !== 0) {
						uni.showToast({
							title: res.msg || '加载失败',
							icon: 'none'
						});
						return;
					}
					
					const records = res.data.records || [];
					// 更新总页数
					this.totalPages = res.data.pages || 1;
					
					// 重置或追加数据
					if (reset && !this.loadingAllData) {
						this.exchangeList = records;
					} else {
						this.exchangeList = [...this.exchangeList, ...records];
					}
					
					// 判断是否有更多数据可加载
					this.hasMore = this.pageNo < this.totalPages;
				} catch (error) {
					console.error('加载兑换记录失败:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
					// 出错时停止加载所有数据的循环
					if (this.loadingAllData) {
						throw error;
					}
				} finally {
					// 如果不是在加载所有数据，则重置各种状态
					if (!this.loadingAllData) {
						this.refreshing = false;
						this.loadingMore = false;
						this.loading = false;
						// 停止系统下拉刷新动画
						uni.stopPullDownRefresh();
					}
				}
			},
			
			// 加载申请记录数据
			async loadApplyData(reset = false) {
				try {
					// 如果已经在加载所有数据，则不重置页码和刷新状态
					if (reset && !this.loadingAllData) {
						this.pageNo = 1;
					}
					
					const token = uni.getStorageSync('token');
					if (!token) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						return;
					}
					
					const requestData = {
						page: this.pageNo,
						limit: this.pageSize,
						type: "1" // 1 表示我的申请
					};
					
					// 调用接口，保持与GoodsDetails一致的请求风格
					const res = await util.request(
						api.integralExchangeRecordUrl,
						requestData,
						'POST'
					);
					
					console.log('申请记录数据:', res);
					
					if (res.code !== 0) {
						uni.showToast({
							title: res.msg || '加载失败',
							icon: 'none'
						});
						return;
					}
					
					const records = res.data.records || [];
					// 更新总页数
					this.totalPages = res.data.pages || 1;
					
					// 重置或追加数据
					if (reset && !this.loadingAllData) {
						this.applyList = records;
					} else {
						this.applyList = [...this.applyList, ...records];
					}
					
					// 判断是否有更多数据可加载
					this.hasMore = this.pageNo < this.totalPages;
				} catch (error) {
					console.error('加载申请记录失败:', error);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
					// 出错时停止加载所有数据的循环
					if (this.loadingAllData) {
						throw error;
					}
				} finally {
					// 如果不是在加载所有数据，则重置各种状态
					if (!this.loadingAllData) {
						this.refreshing = false;
						this.loadingMore = false;
						this.loading = false;
						uni.stopPullDownRefresh();
					}
				}
			},
			
			// 处理划拨操作 - 修改为跳转到划拨页面
			handleApprove(item) {
				console.log('准备划拨:', item);
				// 只传递ID参数，详情数据由API获取
				uni.navigateTo({
					url: `/pages/indexChild/Exchangerecords/ApproveExchange?id=${item.id}`
				});
			},
			
			// 处理取消操作
			handleCancel(item) {
				uni.showModal({
					title: '确认',
					content: `确定要取消商品 "${item.goodsName}" 的兑换申请吗？`,
					success: async (res) => {
						if (res.confirm) {
							try {
								// 调用取消API，保持与GoodsDetails一致的请求风格
								const cancelRes = await util.request(
									api.cancelExchangeUrl + '/' + item.id,
									{},
									'POST'
								);
								
								console.log('取消兑换结果:', cancelRes);
								
								if (cancelRes.code !== 0) {
									uni.showToast({
										title: cancelRes.msg || '取消失败',
										icon: 'none'
									});
									return;
								}
								
								uni.showToast({
									title: '取消成功',
									icon: 'success'
								});
								
								// 刷新列表
								this.onRefresh();
							} catch (error) {
								console.error('取消兑换失败:', error);
								uni.showToast({
									title: '网络错误',
									icon: 'none'
								});
							}
						}
					}
				});
			},
			
			// 查看兑换详情
			viewDetail(item) {
				if(this.activeTab==0){
					uni.navigateTo({
						url: `/pages/indexChild/Exchangerecords/ExchangeDetail?id=${item.id}`
					});
				}else{
					uni.navigateTo({
						url: `/pages/indexChild/Exchangerecords/ExchangeDetail2?id=${item.id}`
					});
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f5f5f5;
	}
	
	/* 标签切换样式 */
	.tabs {
		display: flex;
		position: relative;
		background-color: #fff;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #eee;
		
		.tab-item {
			flex: 1;
			text-align: center;
			font-size: 30rpx;
			color: #666;
			position: relative;
			z-index: 1;
			
			&.active {
				color: #6A9FFB;
				font-weight: 500;
			}
		}
		
		.tab-line {
			position: absolute;
			bottom: 10rpx; /* 调整底部距离 */
			width: 60rpx;
			height: 6rpx;
			background-color: #6A9FFB;
			border-radius: 3rpx;
			transition: left 0.3s;
			transform: translateX(-50%);
		}
	}
	
	/* 滚动区域 */
	.records-scroll {
		flex: 1;
		height: 0;
	}
	
	/* 记录列表 */
	.record-list {
		padding: 20rpx;
	}
    
    /* 加载容器 */
    .loading-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 60rpx 0;
        
        .loading-spinner {
            width: 60rpx;
            height: 60rpx;
            border: 6rpx solid #f3f3f3;
            border-top: 6rpx solid #6A9FFB;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 20rpx;
        }
        
        text {
            color: #999;
            font-size: 28rpx;
        }
    }
    
    @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
	
	/* 单个记录项 */
	.record-item {
		background-color: #fff;
		border-radius: 10rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.05);
		
		.item-main {
			display: flex;
			align-items: center; 
		}
        
        .goods-image {
            width: 120rpx;
            height: 120rpx;
            border-radius: 8rpx;
            margin-right: 20rpx;
            background-color: #f0f0f0; 
            flex-shrink: 0; 
        }
        
        .item-info-wrapper {
            flex: 1; 
            min-width: 0; 
            
            .goods-title-line {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 10rpx;
                
                .goods-name {
                    font-size: 30rpx;
                    font-weight: 500;
                    color: #333;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    margin-right: 10rpx;
                }
                
                .goods-code {
                    font-size: 28rpx;
                    color: #999;
                    white-space: nowrap;
                    flex-shrink: 0;
                }
            }
            
            .item-info {
                font-size: 26rpx; 
                color: #666;
                margin-bottom: 6rpx; 
                display: flex;
                align-items: center;
                overflow: hidden;
                
                .info-label {
                    color: #999;
                    margin-right: 5rpx; 
                    white-space: nowrap; 
                }
                
                .info-content {
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
                
                &:last-child {
                    margin-bottom: 0;
                }
            }
        }
        
        .item-points {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-top: 15rpx;
            
            .points-icon {
                width: 36rpx; 
                height: 36rpx;
                margin-right: 8rpx;
            }
            
            .points-value {
                font-size: 30rpx; 
                color: #FF5B5B;
                font-weight: 500;
                white-space: nowrap; 
            }
        }
		
		.item-actions {
            display: flex;
            justify-content: space-around;
            margin-top: 20rpx;
            border-top: 1rpx solid #f5f5f5;
            padding-top: 20rpx;
			
			.action-btn {
				display: flex;
				align-items: center;
                margin: 0;
                padding: 0 10rpx;
				
				.action-icon {
					width: 36rpx;
					height: 36rpx;
					margin-right: 8rpx;
				}
				
				text {
					font-size: 28rpx;
					color: #666;
                    white-space: nowrap;
				}
			}
			
			.approve-btn text {
				color: #666;
			}
			
			.cancel-btn text {
				color: #666;
			}
			
			.detail-btn text {
				color: #666;
			}

            .complete-btn {
                text {
                    color: #666;
                }
            }
		}
	}
	
	/* 加载更多/无更多 */
	.load-more {
		text-align: center;
		padding: 20rpx 0 40rpx;
		color: #999;
		font-size: 26rpx;
	}
	
	/* 空列表提示 */
	.empty-tip {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
	}
</style>
